package com.mydemo.springlearning.common.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hd
 * @date 2022/2/8 16:02
 */
@Slf4j
@WebFilter(filterName = "loggerFilter", urlPatterns = "/*")
public class LoggerFilter implements Filter {

    private final String X_REQUEST_ID = "X-Request-ID";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.warn("-->>> init");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.warn("-->>> do filter");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        try {
            log.debug("==============================start==============================================");
            log.debug(("请求开始===uri:" + req.getRequestURI()));
            log.debug("请求开始===地址:" + req.getRequestURL());
            log.debug("请求开始===类型:" + req.getMethod());
            log.debug("请求开始===参数String:" + req.getQueryString());
            log.debug("请求开始===参数Map:" + JSON.toJSONString(req.getParameterMap()));
            log.debug("===============================end===============================================");
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            log.debug("ResponseCode: {}", res.getStatus());
        }
    }

    @Override
    public void destroy() {
        log.warn("-->>> destroy");
        Filter.super.destroy();
    }
}
